package com.carrental.vehicle.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.util.SnowflakeIdGenerator;
import com.carrental.vehicle.dto.ImageCollectionDTO;
import com.carrental.vehicle.entity.Image;
import com.carrental.vehicle.entity.ImageCollection;
import com.carrental.vehicle.entity.ImageCollectionRelation;
import com.carrental.vehicle.mapper.ImageCollectionMapper;
import com.carrental.vehicle.mapper.ImageCollectionRelationMapper;
import com.carrental.vehicle.mapper.ImageMapper;
import com.carrental.vehicle.service.ImageCollectionService;
import com.carrental.vehicle.service.ImageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 图片集合服务实现类
 */
@Service
@RequiredArgsConstructor
public class ImageCollectionServiceImpl extends ServiceImpl<ImageCollectionMapper, ImageCollection> implements ImageCollectionService {

    private final ImageCollectionRelationMapper relationMapper;
    private final ImageMapper imageMapper;
    private final ImageService imageService;

    @Override
    public IPage<ImageCollection> pageList(Integer current, Integer size, String name, Long categoryId) {
        LambdaQueryWrapper<ImageCollection> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.hasText(name)) {
            queryWrapper.like(ImageCollection::getName, name);
        }
        
        if (categoryId != null) {
            queryWrapper.eq(ImageCollection::getCategoryId, categoryId);
        }
        
        queryWrapper.orderByAsc(ImageCollection::getSort);
        
        Page<ImageCollection> page = new Page<>(current, size);
        return this.page(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addCollection(ImageCollection imageCollection) {
        imageCollection.setCreateTime(LocalDateTime.now());
        imageCollection.setUpdateTime(LocalDateTime.now());
        return this.save(imageCollection);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCollection(ImageCollection imageCollection) {
        imageCollection.setUpdateTime(LocalDateTime.now());
        return this.updateById(imageCollection);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCollection(Long id) {
        // 先删除关联关系
        LambdaQueryWrapper<ImageCollectionRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImageCollectionRelation::getCollectionId, id);
        relationMapper.delete(queryWrapper);
        
        // 再删除图片集合
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Integer status) {
        ImageCollection collection = new ImageCollection();
        collection.setId(id);
        collection.setStatus(status);
        collection.setUpdateTime(LocalDateTime.now());
        return this.updateById(collection);
    }

    @Override
    public IPage<Image> getCollectionImages(Integer current, Integer size, Long collectionId) {
        // 分页查询图片集合中的图片
        Page<Image> page = new Page<>(current, size);
        
        // 先查询关联关系获取图片ID列表
        LambdaQueryWrapper<ImageCollectionRelation> relationQuery = new LambdaQueryWrapper<>();
        relationQuery.eq(ImageCollectionRelation::getCollectionId, collectionId);
        relationQuery.orderByAsc(ImageCollectionRelation::getSort);
        
        // 计算分页偏移量
        relationQuery.last("LIMIT " + (current - 1) * size + "," + size);
        List<ImageCollectionRelation> relations = relationMapper.selectList(relationQuery);
        
        if (relations.isEmpty()) {
            page.setRecords(new ArrayList<>());
            page.setTotal(0);
            return page;
        }
        
        // 获取图片ID列表
        List<Long> imageIds = relations.stream()
                .map(ImageCollectionRelation::getImageId)
                .collect(Collectors.toList());
        
        // 查询图片信息
        LambdaQueryWrapper<Image> imageQuery = new LambdaQueryWrapper<>();
        imageQuery.in(Image::getId, imageIds);
        List<Image> images = imageMapper.selectList(imageQuery);
        
        // 计算总数
        LambdaQueryWrapper<ImageCollectionRelation> countQuery = new LambdaQueryWrapper<>();
        countQuery.eq(ImageCollectionRelation::getCollectionId, collectionId);
        long total = relationMapper.selectCount(countQuery);
        
        page.setRecords(images);
        page.setTotal(total);
        
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addImageToCollection(ImageCollectionDTO imageCollectionDTO, Long imageId) {

        Image image = new Image();
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(1, 1);
        image.setId(idGenerator.nextId());
        image.setName(imageCollectionDTO.getName());
        image.setUrl(imageCollectionDTO.getUrl());
        image.setCategoryId(imageCollectionDTO.getCollectionId());
        image.setDescription(imageCollectionDTO.getDescription());
        image.setSort(imageCollectionDTO.getSort());
      //  imageService.addImage(image);
        // 检查是否已存在关联
//        LambdaQueryWrapper<ImageCollectionRelation> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(ImageCollectionRelation::getCollectionId, collectionId);
//        queryWrapper.eq(ImageCollectionRelation::getImageId, imageId);
//        if (relationMapper.selectCount(queryWrapper) > 0) {
//            return true; // 已存在关联，视为添加成功
//        }
//
//
//
        // 获取当前最大排序值
        Integer maxSort = getMaxSortByCollectionId(imageCollectionDTO.getCollectionId());
//
        // 创建关联关系
        ImageCollectionRelation relation = new ImageCollectionRelation();
        relation.setCollectionId(imageCollectionDTO.getCollectionId());
        relation.setImageId(image.getId());
        relation.setSort(maxSort + 1);
        relation.setCreateTime(LocalDateTime.now());
        relationMapper.insert(relation);
        return imageMapper.insert(image) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchAddImagesToCollection(Long collectionId, List<Long> imageIds) {
        if (imageIds == null || imageIds.isEmpty()) {
            return false;
        }
        
        // 获取已存在的关联
        LambdaQueryWrapper<ImageCollectionRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImageCollectionRelation::getCollectionId, collectionId);
        queryWrapper.in(ImageCollectionRelation::getImageId, imageIds);
        List<ImageCollectionRelation> existRelations = relationMapper.selectList(queryWrapper);
        
        // 过滤出未关联的图片ID
        List<Long> existImageIds = existRelations.stream()
                .map(ImageCollectionRelation::getImageId)
                .collect(Collectors.toList());
        List<Long> newImageIds = imageIds.stream()
                .filter(id -> !existImageIds.contains(id))
                .collect(Collectors.toList());
        
        if (newImageIds.isEmpty()) {
            return true; // 所有图片已关联，视为添加成功
        }
        
        // 获取当前最大排序值
        Integer maxSort = getMaxSortByCollectionId(collectionId);
        
        // 批量创建关联关系
        List<ImageCollectionRelation> relations = new ArrayList<>();
        for (int i = 0; i < newImageIds.size(); i++) {
            ImageCollectionRelation relation = new ImageCollectionRelation();
            relation.setCollectionId(collectionId);
            relation.setImageId(newImageIds.get(i));
            relation.setSort(maxSort + i + 1);
            relation.setCreateTime(LocalDateTime.now());
            relations.add(relation);
        }
        
        for (ImageCollectionRelation relation : relations) {
            relationMapper.insert(relation);
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeImageFromCollection(Long collectionId, Long imageId) {
        LambdaQueryWrapper<ImageCollectionRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImageCollectionRelation::getCollectionId, collectionId);
        queryWrapper.eq(ImageCollectionRelation::getImageId, imageId);
        
        return relationMapper.delete(queryWrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemoveImagesFromCollection(Long collectionId, List<Long> imageIds) {
        if (imageIds == null || imageIds.isEmpty()) {
            return false;
        }
        
        LambdaQueryWrapper<ImageCollectionRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImageCollectionRelation::getCollectionId, collectionId);
        queryWrapper.in(ImageCollectionRelation::getImageId, imageIds);
        
        return relationMapper.delete(queryWrapper) > 0;
    }
    
    /**
     * 获取图片集合中的最大排序值
     * 
     * @param collectionId 图片集合ID
     * @return 最大排序值，如果没有则返回0
     */
    private Integer getMaxSortByCollectionId(Long collectionId) {
        LambdaQueryWrapper<ImageCollectionRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImageCollectionRelation::getCollectionId, collectionId);
        queryWrapper.orderByDesc(ImageCollectionRelation::getSort);
        queryWrapper.last("LIMIT 1");
        
        ImageCollectionRelation relation = relationMapper.selectOne(queryWrapper);
        return relation != null ? relation.getSort() : 0;
    }
} 